<?php
namespace app\index\controller;

use app\admin\model\halt\Cate;
use app\admin\model\Houseout;
use app\admin\model\Stock;
use app\admin\model\Supplier;
use think\Db;

class Fgs extends Store
{
    public $manger=['ZhanZhiWei','ZhanZhiWei'];
    public $caosong=['ZhanZhiWei'];//['HanXiaoFang','LiSuWei'];
    public $changePerson='ZhanZhiWei';
    public $viewArr=['ZhangWwei','LiuQianRan'];
    public function _initialize()
    {
        parent::_initialize();
    }
    public function index()
    {

        $list = Db::name("githouse")->field('id,gname,dep')->where(array("manger"=>$this->user['userid']))->find();
        $where=array();
        $isShowCk=0;
        $isAdd=0;
        $userid = $this->user['userid'];
        //仓库管理员
        if ($list){
            $cid=$list['id'];
            $isAdd=1;
            $where['cid']=array('eq',$cid);
        }else{
            //获取所在公司
            $depList = check_Department($this->auth->department,1);
            if (!$depList){
                //总部
                if (!in_array($userid,$this->manger) && !in_array($userid,$this->caosong) && !in_array($userid,$this->viewArr) && $this->changePerson!=$userid){
                    $this->error('没有权限');
                }
                if (!$this->request->isAjax()) {
                    $isShowCk=1;//开关仓库搜索选项
                    $gitList = Db::name("githouse")->field('id,gname')->where(array("id"=>array('neq',1)))->select();
                    $this->view->assign("gitList",$gitList);

                }
                    //获取当前是否是上级

            }else{

                if ($this->getLeader($depList)!=$userid)$this->error('没有权限');
                $where['sub']=$depList;
            }
        }
        if ($this->request->isAjax()){
            $page = isset($_POST['counter']) ? intval($_POST['counter']) : 1;
            $offset = 4*($page-1);
            if (isset($_POST['status'])){
                $status = $_POST['status'];
                if ($status==9){
                    $where['status']=array('in',array(9,8,7));
                }else{
                    $where['status']=array('eq',$status);

                }
            }

            if (isset($_POST['supplier'])){
                $supplier = $_POST['supplier'];
                $where['cid']=$supplier;
            }

            $info = Db::name("purin")->where($where)->limit($offset,4)->order("id desc")->select();
            foreach ($info as $k=>$v){
                $info[$k]['createtime']=date("Y-m-d");
                $info[$k]['publisher']=$this->getPublisher($v['publisher']);
                $info[$k]['status']=$this->getStatus($v['status']);
                $g=Db::name("githouse")->field("gname")->find($v['cid']);
                $info[$k]['cname']=$g['gname'];
            }

            $result = array("list"=>$info);

            return json($result);

        }
        $this->view->assign("isshow",$isShowCk);
        $this->view->assign("isAdd",$isAdd);

        return $this->view->fetch();

    }
    public function add(){
        //获取所在分公司
        $depList = check_Department($this->auth->department,1);
        if (!$depList)$this->error('当前没有所在分公司');
        $house = Db::name("githouse")->field('id,gname,dep')->where(array("dep"=>$depList))->find();
        if (!$house)$this->error('当前公司没有创建仓库');
        $this->view->assign("bh",date("Ymd").substr(time(),6).random(4,1));
        $this->view->assign("username",$this->getPublisher($this->user['userid']));
        $preCate = Db::name("halt_cate")->field('id,pid,name')->where(array("type"=>1,"pid"=>0,'id'=>226))->order("id asc")->select();
        $firstCate=$preCate[0]['id'];
        $cate = Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$firstCate))->order("id asc")->select();
        foreach ($cate as $k=>$v){
            $cate[$k]['cateArr']=Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$v['id']))->order("id asc")->select();
        }

        $this->view->assign("preCate", $preCate);
        $this->view->assign("cate", $cate);

        return $this->view->fetch();

    }
    //分公司要货
    public function inStore()
    {

        $list = Db::name("githouse")->field('id,gname,dep')->where(array("manger"=>$this->user['userid']))->find();
        if (!$list)$this->error('您不是仓库管理员');

        if ($this->request->isPost() && isset($_POST['sub'])) {
            $post = $_POST;
            $post['createtime']=strtotime($post['riqi']);
            $post['publisher']=$this->user['userid'];
            $shopList = $post['shopList'];
            unset($post['riqi'],$post['shopList'],$post['sub'],$post['total_money'],$post['total']);
            $this->checkStore($shopList);//检查库存是否充足
            $post['sub']=$list['dep'];
            $post['cid']=$list['id'];
            $leader=$this->getLeader($list['dep']);
            Db::startTrans();//开启事务
            $pid = Db::name("purin")->insert($post,0,1);
            if (!$pid) {
                Db::rollback();
                $this->error("订单号重复");
            }
            foreach ($shopList as $k=>$v){
                $check=Db::name('purin_data')->insert(array('shopid'=>$v['id'],'num'=>$v['num'],'nums'=>$v['num'],'pur_id'=>$pid));
                if (!$check)break;
            }

            if (!$check){
                Db::rollback();
                $this->error("添加失败");
            }else{
                Db::commit();
                if ($post['status']==9){

                    //发送推送通知
                    $this->sendText("待审核通知","<div class=\"gray\">审核：".$this->getPublisher($this->user['userid']).".有入库单需要审核，请前往处理</div>",$this->host."index/fgs/view/id/".$pid,'ZhanZhiWei');

                }

                $this->setWork(Db::name("purin")->where(array("id"=>$pid))->find(),$post['status'],3);
                $this->success("添加成功");
            }

        }
        $preCate = Db::name("halt_cate")->field('id,pid,name')->where(array("type"=>1,"pid"=>0,'id'=>226))->order("id asc")->select();
        $firstCate=$preCate[0]['id'];
        $cate = Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$firstCate))->order("id asc")->select();
        foreach ($cate as $k=>$v){
            $cate[$k]['cateArr']=Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$v['id']))->order("id asc")->select();
        }

        $this->view->assign("preCate", $preCate);
        $this->view->assign("cate", $cate);


        $this->view->assign("username",$this->getPublisher($this->user['userid']));
        $this->view->assign("gname",$list['gname']);

        $this->view->assign("bh",'YHRK'.date("Ymd").substr(time(),6).random(4,1));
        return $this->view->fetch();

    }
    //操作驳回
    function reject(){
        $id = $this->request->post("id");
        $status = $this->request->post("status");
        $arrStatus=array(9,8,7);
        if (!in_array($status,$arrStatus))$this->error('参数错误');

        $mark = $this->request->post("mark");
        if (!$id || $status=='')$this->error("参数错误");
        if ($mark=='')$this->error("请提交驳回意见");
        if (in_array($status,array(4,1)))$this->error("此订单不能操作");
        $info = Db::name('purin')->where(array('id'=>$id))->find();
        $userid = $this->user['userid'];

        switch ($status){
            case 9:
                $this->getLeader($info['sub'])!=$userid? $this->error('操作错误1') : '';
                break;
            case 8:
                $userid!=$this->manger[0] ? $this->error('操作错误') : '';
                break;
            case 7:
                $userid!=$this->manger[1] ? $this->error('操作错误') : '';

                break;
        }
        DB::name("purin")->where(array("id"=>$id))->update(array("status"=>-4));
        DB::name("purin_work")->insert(array(
            "pid"=>$id,
            "inputtime"=>time(),
            "publisher"=>$userid,
            "mark"=>$mark,
            "status"=>2
        ));
        $this->setWork($info,-4,3);
        $this->sendText("驳回通知","<div class=\"gray\">入库单已被驳回\n原因：{$mark}</div>",$this->host."index/fgs/view/id/".$info['id'],$info['publisher']);

        /*
         * 驳回通知
         * */
        $this->success("操作成功");
    }
    public function edit($id){
        $info = Db::name("purin")->where(array('id'=>$id))->find();
        if (!$info || $info['publisher']!=$this->user['userid'])$this->error('没有权限');
        if ($info['status']==10 || $info['status']=='-4') {
            if ($this->request->isAjax() && $this->request->isPost()){
                $post = $_POST;
                $post['createtime']=strtotime($post['riqi']);
                $shopList = $post['shopList'];
                unset($post['riqi'],$post['shopList']);
                $this->checkStore($shopList);//检查权限
                Db::name("purin")->where(array("id"=>$id))->update($post);
                Db::name('purin_data')->where(array("pur_id"=>$id))->delete();
                foreach ($shopList as $k=>$v){
                    Db::name('purin_data')->insert(array('shopid'=>$v['id'],'num'=>$v['num'],'nums'=>$v['num'],'pur_id'=>$id));
                }
                if ($post['status']==9){
                    $this->sendText("待审核通知","<div class=\"gray\">审核：".$this->getPublisher($this->user['userid']).".有入库单需要审核，请前往处理</div>",$this->host."index/fgs/view/id/".$id,$this->getLeader($info['sub']));
                }
                $this->setWork($info,$post['status']);

                $this->success("编辑成功","/index/fgs/view/id/".$id);
            }
            $preCate = Db::name("halt_cate")->field('id,pid,name')->where(array("type"=>1,"pid"=>0,'id'=>226))->order("id asc")->select();
            $firstCate=$preCate[0]['id'];
            $cate = Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$firstCate))->order("id asc")->select();
            foreach ($cate as $k=>$v){
                $cate[$k]['cateArr']=Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$v['id']))->order("id asc")->select();
            }

            $this->view->assign("preCate", $preCate);
            $this->view->assign("cate", $cate);

            $ginfo = Db::name("githouse")->where(array("id"=>$info['cid']))->find();
            $this->view->assign("gname",$ginfo['gname']);
            $this->view->assign('info',$info);
            $this->view->assign("username",$this->getPublisher($this->user['userid']));
            $purList=Db::name('purin_data')->field('shopid as id,num')->where(array("pur_id"=>$id))->select();
            foreach ($purList as $k=>$v){
                $purList[$k]['number']=$v['num'];
                $purList[$k]['type']=$this->getType($v['id']);
                $purList[$k]['cname']=$this->getCname($v['id']);
                $purList[$k]['storenum']=$this->getStoreNum(1,$v['id']);
            }
            $this->view->assign("purList", json_encode($purList));

            return $this->view->fetch();
        }

    }
    protected function getStoreNum($cid,$id){
        if (!$cid || !$id)return 0;
        $info = Db::name("stock")->where(array("cid"=>$cid,"shopid"=>$id))->find();
        if ($info)return $info['num'];
        return 0;
    }

    public function view($id){

        $info = Db::name("purin")->find($id);
        if (!$info)$this->error('参数错误');
        $info['username']=$this->getPublisher($info['publisher']);
        $info['status_text'] = $this->getStatus($info['status']);

        //获取当前仓库管理人，分公司负责人
        $cid = $info['cid'];
        $leader = $this->getLeader($info['sub']);
        $userid = $this->user['userid'];
        $ginfo = Db::name("githouse")->find($cid);
        if ($leader!=$userid && !in_array($userid,$this->manger) && !in_array($userid,$this->caosong) && $userid!=$info['publisher'])$this->error('您没有权限');
        $info['cidName']=$ginfo['gname'];
        $worklist=[];
        if ($info['status']!=10){
            $worklist = Db::name("purin_work")->where(array("pid" => $id))->select();
            if ($worklist) {
                foreach ($worklist as $k => $v) {
                    $worklist[$k]['user'] = $this->getInfo($v['publisher']);
                }
            }
            if ($info['status']==9){

                $leadInfo=array(
                    'status'=>3,
                    "user"=>$this->getInfo($leader),
                    'mark'=>''
                );
                array_push($worklist,$leadInfo);
            }

        }

        $this->view->assign('worklist',$worklist);


        $this->view->assign("info",$info);

        $userArr=array();
        if ($info['status']==8){
            $userArr[]=$this->manger[0];
        }else if($info['status']==7){
            $userArr[]=$this->manger[1];

        }
        $this->view->assign("userArr",$userArr);

        $this->view->assign("userid",$this->user['userid']);
        $this->view->assign("leader",$leader);

        $list = Db::name('purin_data')->field("shopid,num,nums")->where(array('pur_id' => $id))->select();
        foreach ($list as $k=>$v){
            $list[$k]['cname']=$this->getCname($v['shopid']);
            $list[$k]['types']=$this->getType($v['shopid']);

        }
        $this->view->assign("changePerson",$this->changePerson);

        $this->view->assign("list",$list);

        return $this->view->fetch();
    }
    //右侧按钮提交
    function oper(){
        $id = $this->request->post("id");
        $status = $this->request->post("status");
        if (!$id || $status=='')$this->error("参数错误");
        if (isset($_POST['mark']) && $_POST['mark']){
            $mark = trim($_POST['mark']);
        }

        $userid = $this->user['userid'];
        $info = Db::name('purin')->where(array('id'=>$id))->find();
        if (in_array($status,array(4,1)))$this->error("此订单不能操作");

        switch ($status){
            case 10:
                if ($info['publisher']!=$userid)$this->error("您没有权限");
                //检查权限
                Db::name("purin")->where(array("id"=>$id))->update(array("status"=>9));
                $this->setWork($info,9);
                $this->sendText("待审核通知","<div class=\"gray\">审核：".$this->getPublisher($info['publisher']).".有入库单需要审核，请前往处理</div>",$this->host."index/fgs/view/id/".$info['id'],$this->getLeader($info['sub']));
                $this->success("操作成功");
                break;
            case 9:
                $leader = $this->getLeader($info['sub']);
                if ($leader!=$userid)$this->error('您没有权限');
                $this->setStatus($info,8,$this->manger[0]);
                break;
            case 8:

                if ($this->manger[0]!=$userid)$this->error('您没有权限');
                $this->setStatus($info,7,$this->manger[1]);
                break;
            case 7:

                if ($this->manger[1]!=$userid)$this->error('您没有权限');
                $this->setStatus($info,5,'');
                break;
            case 5:
                //入库操作
                if ($info['publisher']!=$userid)$this->error("您没有权限");
                $arrData = Db::name("purin_data")->where(array("pur_id"=>$info['id']))->field("shopid as id,nums as num")->select();
                $this->checkStore($arrData);//检测库存是否充足
                Db::name("purin")->where(array("id"=>$info['id']))->update(array("status"=>1));
                $this->setWork($info,1);
                gzy_reduce_stock($info['cid'],$arrData,$userid);
                break;
            case -2:

                if ($this->changePerson!=$userid)$this->error('您没有权限');
                $this->setStatus($info,-20);
                break;
            case -4:
                if ($info['publisher']!=$userid)$this->error("您没有权限");
                $this->setStatus($info,-1);
                break;
            case '-20':
                //入库操作
                if ($info['publisher']!=$userid)$this->error("您没有权限");
                $arrData = Db::name("purin_data")->where(array("pur_id"=>$info['id']))->field("shopid as id,nums as num")->select();
                $this->checkStore($arrData);//检测库存是否充足
                Db::name("purin")->where(array("id"=>$info['id']))->update(array("status"=>1));
                $this->setWork($info,1);
                gzy_reduce_stock($info['cid'],$arrData,$userid);
                break;

        }
        $this->success("操作成功");

    }
    function change(){
        $id = $this->request->post("id");

        if (!$id)$this->error("参数错误");
        $userid = $this->user['userid'];
        $info = Db::name('purin')->where(array('id'=>$id))->find();
        if (!in_array($info['status'],array(5,-2,-21)))$this->error("参数错误");
        if ($info['status']==-2){
            if ($userid!=$this->changePerson)$this->error('没有权限');
            Db::name('purin')->where(array('id'=>$id))->update(array('status'=>-21));
            $this->sendText("通知","<div class=\"gray\">要库单号".$info['order_id'].".已被拒绝，请查看</div>",$this->host."index/fgs/view/id/".$info['id'],$info['publisher']);

            $this->success('操作成功');

        }else{
            if ($userid!=$info['publisher'])$this->error('没有权限');
            $post = $_POST['data'];
            foreach ($post as $v){
                Db::name("purin_data")->where(array("pur_id"=>$id,'shopid'=>$v['name']))->update(array("nums"=>$v['value']));

            }
            Db::name('purin')->where(array('id'=>$id))->update(array('status'=>-2));
            $this->setWork($info,-2);
            $this->sendText("待审核通知","<div class=\"gray\">审核：".$this->getPublisher($info['publisher']).".有要货单需要进行变更</div>",$this->host."index/fgs/view/id/".$info['id'],$this->changePerson);

            $this->success('操作成功');
        }


    }
    /*
     * info 当前信息
     * cur  需要设置的状态
     * person 下一位审核人
     * */
    protected function setStatus($info,$cur,$person=''){


        Db::name("purin")->where(array("id"=>$info['id']))->update(array("status"=>$cur));
        if ($cur=='-20'){
            $this->sendText("变更通知","<div class=\"gray\">订单号:".$info['order_id']."已同意变更</div>",$this->host."index/fgs/view/id/".$info['id'],$info['publisher']);
            return true;
        }
        if ($cur==-1)return true;
        Db::name("purin_work")->insert(array(
            "pid"=>$info['id'],
            "inputtime"=>time(),
            "publisher"=>$this->user['userid'],
            "mark"=>'',
            "status"=>1
        ));


        $this->setWork($info,$cur);
        if ($cur==5){
            $this->sendText("操送通知","<div class=\"gray\">有要货单已通过审核\n订单号:".$info['order_id']."</div>",$this->host."index/fgs/view/id/".$info['id'],implode('|',$this->caosong));

            $this->sendText("审核成功","<div class=\"gray\">你的要货单已经通过审核，请前往查看</div>",$this->host."index/fgs/view/id/".$info['id'],$info['publisher']);

        }else{
            $this->sendText("待审核通知","<div class=\"gray\">审核：".$this->getPublisher($info['publisher']).".有要货单需要审核，请前往处理</div>",$this->host."index/fgs/view/id/".$info['id'],$person);

        }


    }
    //当前产品半成品和成品
    protected function getType($id){
        if (!$id)return false;
        $info = Db::name("preproduct")->field('type')->where(array('id'=>$id))->find();
        if (!$info)return'';
        if ($info['type']==2)return "成品";
        return "半成品";

    }

       //设置工作流
    protected function setWork($info,$status,$type=3){
        $id = $info["id"];

        if ($work = Db::name("workflow")->field("id")->where(array("tid"=>$id,"type"=>$type))->find()){
            Db::name("workflow")->where(array("id"=>$work['id']))->update(array("status"=>$status,"uptime"=>time()));
        }else{
            Db::name("workflow")->insert(array("tid"=>$id,"status"=>$status,"order_id"=>$info['order_id'],"type"=>$type,"inputtime"=>$info['createtime'],"uptime"=>time(), "userid"=>$this->user['userid']));

        }
        return true;

    }
    //检查库存是否充足,总部
    protected function checkStore($arr,$cid=1){
        if (!$arr || !$cid)$this->error("参数错误");
        $temp=0;
        $db = new Stock();
        foreach ($arr as $v){
            $st = $db->where(array("cid"=>$cid,"shopid"=>$v['id']))->find();

            if (!$st || $st['num'] < $v['num']){
                $temp=$v['id'];
                break;
            }
        }
        if ($temp > 0)$this->error($this->getCname($temp)."库存不足");

        return true;
    }

    function getLeader($dep){
        $userList = TableListSqlQuery('Admin',"find_in_set('".$dep."',department) and `isleader` = '1'",'userid');
        if (!$userList)$this->error('当前分公司没有负责人');
        $leader = 'ZhanZhiWei';//$userList[0]['userid'];
        return $leader;
    }
    function getCate1(){
        if (isset($_GET['type'])){
            $type = intval($_GET['type']);
            $where['type']=$type;
            $where['pid']=0;
            if ($type==2){
                $where['id']=array('eq',216);
            }else{
                $where['id']=array('eq',226);

            }
            $list = Db::name("halt_cate")->where($where)->field('id,pid,name')->select();
            $aid = $list[0]['id'];
            $cate = Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$aid))->order("id asc")->select();
            $str='';
            foreach ($cate as $v){
                $str.='  <div class="cate_content_title">
                            <span class="h"></span><span>'.$v['name'].'</span><span class="h"></span>
                        </div>';
                $lists = Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$v['id']))->order("id asc")->select();
                $str.=' <table cellspacing="0" cellpadding="0">
                            <tr>';
                foreach ($lists as $d){
                    $str.=' <td onclick="tdClick(this)" dataid="'.$d['id'].'">'.$d['name'].'</td>';
                }
                $str.='   </tr>
                        </table>';
            }
            return json(array('list'=>$list,'html'=>$str));
        }
    }
    public function getProduct()
    {
        if ($this->request->isAjax()){
            $where=[];
            $post = $_POST;
            $post['cid']=1;
            if (isset($post['pid'])) {

                $where['type'] = $post['type'];
            }
            if (isset($post['pid']) && $post['pid'] > 0){
                $pid = intval($post['pid']);
                $where['classif']=$pid;
            }

            if (isset($post['title']) && $post['title']!=''){
                $title = $_POST['title'];
                $where['cname']=array('like',"%{$title}%");
            }
            $page = isset($_POST['counter']) ? intval($_POST['counter']) : 1;
            $offset = 6*($page-1);
            //仓库开始
            $anywhere['cid']=$post['cid'];
            $anywhere['num']=array('gt',0);
            $stock=array_column(Db::name('stock')->where($anywhere)->field('shopid as id,cid,num')->select(),'id');
            if (!$stock)return json(array('list'=>[]));
            $where['id']=array('in',implode(',',$stock));
            //仓库结束
            $info = Db::name('preproduct')->where($where)->limit($offset,6)->select();
            foreach($info as $k=>$v){
                if ($v['type']==2){
                    $info[$k]['type']="成品";
                }else{
                    $info[$k]['type']="半成品";
                }

                $info[$k]['storenum']=$this->getStore($v['id'],$post['cid']);
            }

            $result = array("list"=>$info);
            return json($result);


        }
    }
}